package deployr.client.http;

import static deployr.client.http.Streams.*;
import static java.text.MessageFormat.*;

import java.io.*;
import java.net.*;

import deployr.client.api.*;

public class UploadHttpClient implements UploadApi {

	@Override
	public void upload(String deployrUrl, String updateKey, File file) {
		boolean uploaded = tryUpload(deployrUrl, updateKey, file);
		if (!uploaded) uploaded = tryUpload(deployrUrl, updateKey, file);
		if (!uploaded) uploaded = tryUpload(deployrUrl, updateKey, file);
		if (uploaded) return;
		throw new RuntimeException(format("problem updating {0}", file));
	}

	private boolean tryUpload(String deployrUrl, String updateKey, File file) {
		try {
			String format = format("{0}/updates/{1}/files/{2}/bytes", deployrUrl, updateKey, file.getName());
			URL url = new URL(format);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			OutputStream outputStream = conn.getOutputStream();
			copy(file, outputStream);
			outputStream.flush();
			outputStream.close();
			InputStream inputStream = conn.getInputStream();
			inputStream.close();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

}
